/*
 * @Description: 文件预览组件
 * @Author: Rfan
 * @Date: 2022-03-03 15:28:57
 * @LastEditTime: 2023-01-31 16:18:34
 */

import { CSSProperties, useEffect, useState } from 'react';
import { Button, Collapse, Divider, Form, Modal, Space, Table } from 'antd';
import classNames from 'classnames/bind';
import { ExpandOutlined, CompressOutlined } from '@ant-design/icons';
import PDFViewer from './components/PDFViewer';
import VideoViewer from './components/VideoViewer';
import ImageViewer from './components/ImageViewer';
import type { IMetadata } from '@/interfaces/metadata';
import type { ICommonDialog } from '@/interfaces/global';
import styles from './styles/index.module.scss';
import MediaInformation from '@/components/Preview/components/MediaInfo';
import RecordDownload from '../functionalBtns/RecordDownload';
import cs from 'classnames';
const cx = classNames.bind(styles);

const { Panel } = Collapse;
const { Column } = Table;

// 各种文件类型列表
const pdfExts = ['pdf'];
const ofdExts = ['ofd'];
const videoExts = ['mp4', 'avi', 'flv', 'wmv'];
const audioExts = ['mp3', 'wav', 'flac', 'ogg'];
const imageExts = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
const otherExts = pdfExts.concat(ofdExts, videoExts, audioExts, imageExts);

interface IPreviewProps extends ICommonDialog {
  title: string;
  data: IMetadata | {};
  list: IMetadata[];
  upper?: any;
  fields?: any[];
  baseInfo?: any;
  width?: string | number;
  style?: CSSProperties;
}

// 预览组件开始
const Preview = (props: IPreviewProps) => {
  const { visible, title, list, data, width, style, onClose, upper, fields, baseInfo } = props;
  // 选中的电子文件
  const [selectItem, setSelectItem] = useState<any>({});
  // 选中的文件类型
  const [fileType, setFileType] = useState('');
  // 放大缩小用
  const [amplify, setAmplify] = useState(false);
  // 媒体信息类型
  const [commonMedia, setCommonMedia] = useState(null);

  /* 页面数据刷新赋值 */
  useEffect(() => {
    console.log({ upper, fields });

    const _selectItem: any = data || list[0];

    setSelectItem(_selectItem);
    setAmplify(false);
  }, [data]);

  useEffect(() => {
    if (selectItem?.file_ext) {
      setFileType(selectItem.file_ext);
    }
    if (selectItem) {
      setCommonMedia({
        文件名: selectItem.file_name,
        大小: selectItem.file_size,
        拓展名: selectItem.file_ext
      });
    }
  }, [selectItem]);

  /* 条目信息转换 */
  const ResultInfo = ({ info, fields }: any) => {
    return fields.map((item: any) => (
      <Form.Item label={item.field_desc}>
        <span dangerouslySetInnerHTML={{ __html: info[item.field_name] }}></span>
      </Form.Item>
    ));
  };

  /**
   * @description: 关闭弹窗
   */
  const onCancel = () => {
    onClose();
  };

  /**
   * @description: 模态框确认按钮事件
   */
  const handleOk = () => {
    onCancel();
  };

  /**
   * @description: 表格单击操作，用于设置选中行状态，单选
   * @param {any} record
   * @return {*}
   */
  const handleRow = (record: any) => {
    return {
      onClick: () => {
        setSelectItem(record);
      }
    };
  };
  const setRowClass = (record: any) => {
    return record.id === selectItem.id ? 'ant-table-row-selected' : '';
  };
  /* 页面放大缩小判断 */
  const enlarge = () => {
    setAmplify(!amplify);
  };

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      width={width || 1000}
      style={style}
      footer={null}
      maskClosable={false}
      wrapClassName={cs(cx('jp-preview'), { 'jp-modal-fullscreen': amplify })}
      {...props}
    >
      <div className={cx('preview-wrap')}>
        <div className={cx('nav')}>
          <Collapse defaultActiveKey={['1', '2']}>
            <Panel header="文件条目信息" key="1" showArrow={false} collapsible="disabled">
              {/* 遍历显示信息 */}
              {upper && fields && (
                <Form size="small" className={cx('record-info')}>
                  <ResultInfo info={upper} fields={fields} />
                </Form>
              )}
            </Panel>
            <Panel header="电子原文列表" key="2" showArrow={false} collapsible="disabled">
              <div className={cx('e-record__table')}>
                <Table
                  showHeader={false}
                  dataSource={list}
                  size="small"
                  rowKey="id"
                  pagination={false}
                  onRow={handleRow}
                  rowClassName={setRowClass}
                  bordered
                >
                  <Column dataIndex="id" key="id" align="center" />
                  <Column dataIndex="title" key="title" />
                </Table>
              </div>
            </Panel>
          </Collapse>
        </div>
        <div className={cx('content')}>
          <div className={cx('operate')}>
            <h4>{selectItem.title}</h4>
            <Space>
              {/* 媒体信息下拉 */}
              <MediaInformation selectItem={selectItem} commonMedia={commonMedia} />
              {/* 下载 */}
              <RecordDownload selectItems={[selectItem.id]} type={'text'} baseInfo={baseInfo} />
              <Button type="text" size="small">
                收藏文件
              </Button>
              <Button type="text" size="small">
                档案篮子
              </Button>
              <Button type="text" size="small">
                借阅利用
              </Button>
              <Button type="text" size="small">
                摘录
              </Button>
              <Divider type="vertical" />
              <Button
                type="link"
                onClick={enlarge}
                style={amplify ? { display: 'none' } : {}}
                size="small"
              >
                <ExpandOutlined />
              </Button>
              <Button
                type="link"
                onClick={enlarge}
                style={amplify ? {} : { display: 'none' }}
                size="small"
              >
                <CompressOutlined />
              </Button>
            </Space>
          </div>
          <div className={cx('detail')}>
            {pdfExts.indexOf(fileType) >= 0 && (
              <PDFViewer title="PDF" src={selectItem.preview_url} />
            )}
            {ofdExts.indexOf(fileType) >= 0 && (
              <PDFViewer title="OFD" src={selectItem.preview_url} />
            )}
            {videoExts.indexOf(fileType) >= 0 && selectItem.file_url && (
              <VideoViewer
                type={`video/${fileType}`}
                src={selectItem.preview_url || selectItem.file_url}
              />
            )}
            {audioExts.indexOf(fileType) >= 0 && (
              <VideoViewer
                type={`audio/${fileType}`}
                src={selectItem.preview_url || selectItem.file_url}
              />
            )}
            {imageExts.indexOf(fileType) >= 0 && <ImageViewer selectItem={selectItem} />}
            {otherExts.indexOf(fileType) < 0 && (
              <PDFViewer title="PDF" src={selectItem.preview_url} />
            )}
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default Preview;
